<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-11-08
 * Time: 11:31:12
 * Info:
 */

namespace app\common\model;

class ContentKeywords extends TimeInit
{

    /**
     * 获取对应文章数量
     * @return int
     */
    public function contentCount($kid = 0)
    {
        return $this->where(function ($query) use ($kid) {
            if ( ! empty($kid)) {
                $query->where('keywords_id', $kid);
            }
        })->count();
    }

    /**
     * 文章关键词关联操作
     */
    public function articleKeywordsEdit(int $articleId, string $keywordNames = "")
    {
        $this->where(['aid' => $articleId])->delete();
        $keywordArray = array_filter(explode(',', $keywordNames));
        if ( ! empty($keywordArray)) {
            $this->insertKeyword($keywordArray, $articleId);
        }
    }

    public function insertKeyword(array $keywordArray = [], int $aid = 0)
    {
        if (empty($keywordArray)) {
            return;
        }
        $insert = [];
        $time   = time();
        foreach ($keywordArray as $key => $value) {
            if ( ! $value) {
                continue;
            }
            $keywords_id = (new Keywords())->increase($value);
            $insert[]    = [
                'aid'         => $aid,
                'keywords_id' => $keywords_id,
                'create_time' => $time,
            ];
        }
        $res = $this->strict(false)->field(true)->insertAll($insert);

        return $res;
    }

    //删除关键词
    public function deleteKeyword($keywordsId)
    {
        $res = $this->where('keywords_id', $keywordsId)->delete();

        return $res;
    }
}
